package com.jds.clickhouse.web.service.impl.sys;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jds.link4sales.model.entity.sys.SysDept;
import com.jds.link4sales.model.mapper.sys.SysDeptMapper;
import com.jds.link4sales.model.mapper.sys.SysUserMapper;
import com.jds.link4sales.model.vo.SysDeptTreeVo;
import com.jds.clickhouse.web.service.sys.SysDeptService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2020-11-03
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    private final SysDeptMapper sysDeptMapper;

    private final SysUserMapper sysUserMapper;

    // 内存查询，避免多次查库
    private Map<String, List<SysDeptTreeVo>> deptMap;

    private Map<String, List<SysDeptTreeVo>> userMap;

    @Override
    public SysDeptTreeVo getTree() {
        String parentId = "1";
        int queryNum = 1;
        List<SysDeptTreeVo> deptList = sysDeptMapper.selectTreeInfo();
        deptMap = deptList.stream().collect(Collectors.groupingBy(SysDeptTreeVo::getParentId));
        List<SysDeptTreeVo> userList = sysUserMapper.selectTreeInfo();
        userMap = userList.stream().collect(Collectors.groupingBy(SysDeptTreeVo::getParentId));
        SysDeptTreeVo node = SysDeptTreeVo.builder().id(parentId).name("root").build();
        selectByParentId(node, parentId, queryNum);
        return node;
    }

    private void selectByParentId(SysDeptTreeVo node, String parentId, int queryNum) {
        List<SysDeptTreeVo> deptList = deptMap.get(parentId);
        List<SysDeptTreeVo> userList = userMap.get(parentId);
        if (queryNum < 20) {
            queryNum++;
            if (deptList != null) {
                for (SysDeptTreeVo sysDept : deptList) {
                    selectByParentId(sysDept, sysDept.getId(), queryNum);
                }
            }
        } else {
            log.error("递归层数溢出，可能存在异常数据！node：{}", node);
        }
        if (deptList != null) {
            if (userList != null) {
                // 添加用户节点
                deptList.addAll(userList);
            }
            // 添加部门节点
            node.setList(deptList);
        } else {
            // 添加用户节点
            node.setList(userList);
        }
    }

}
